<?php

namespace app\admin\controller\bargain;

use app\common\controller\AdminController;
use app\common\lib\Show;
use app\common\lib\Status;
use think\App;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;

/**
 * @ControllerAnnotation(title="砍价管理")
 */
class Bargain extends AdminController
{

    use \app\admin\traits\Curd;
    protected array $withAttr = [];

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\common\model\BargainBargain();

        $this->assign('getStatusList', $this->model->getStatusList());
        $this->assign('getHalfwayList', $this->model->getHalfwayList());
        $this->assign('getNumberList', $this->model->getNumberList());
        $this->assign('getBargainTypeList', $this->model->getBargainTypeList());
        $this->assign('getBargainAddressList', $this->model->getBargainAddressList());
        $this->assign('getPayTypeList', $this->model->getPayTypeList());
        $this->field = "*,start_time as get_start_time,end_time as get_end_time,pay_type as get_pay_type,goods_cate as goods_sku";
    }

    /**
     * @NodeAnotation (title="砍价列表")
     * @return array|mixed|\think\response\Json
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            $get = $this->request->get('', null, null);
            $page = isset($get['page']) && !empty($get['page']) ? $get['page'] : 1;  //获取分页
            $limit = isset($get['limit']) && !empty($get['limit']) ? $get['limit'] : 15;  //获取每页条数
            $filters = isset($get['filter']) && !empty($get['filter']) ? $get['filter'] : '{}';  //ca念书
            $ops = isset($get['op']) && !empty($get['op']) ? $get['op'] : '{}'; //搜索方式
            $filters = json_decode($filters, true);
            $ops = json_decode($ops, true);
            $where = [];
            $goods_name = "";
            if(!empty($filters)){
                foreach ($filters as $key => $val) {
                    if($key == 'goods.title'){
                        $where[] = ['g.title',"like","%{$val}%"];
                    } else  {
                        $op = isset($ops[$key]) && !empty($ops[$key]) ? $ops[$key] : '%*%';

                        switch (strtolower($op)) {
                            case '=':
                                $where[] = ["b.".$key, '=', $val];
                                break;
                            case '%*%':
                                $where[] = ["b.".$key, 'LIKE', "%{$val}%"];
                                break;
                            case '*%':
                                $where[] = ["b.".$key, 'LIKE', "{$val}%"];
                                break;
                            case '%*':
                                $where[] = ["b.".$key, 'LIKE', "%{$val}"];
                                break;
                            case 'range':
                                [$beginTime, $endTime] = explode(' - ', $val);
                                $where[] = ["b.".$key, '>=', strtotime($beginTime)];
                                $where[] = ["b.".$key, '<=', strtotime($endTime)];
                                break;
                            default:
                                $where[] = ["b.".$key, $op, "%{$val}"];
                        }
                    }
                }
            }
            $lists = $this->model
                ->field('b.*,b.start_time as get_start_time,b.end_time as get_end_time,b.pay_type as get_pay_type,b.goods_cate as goods_sku,b.create_time,b.start_time,b.end_time,g.id as gid,g.title as g_title')
                ->alias('b')
                ->join('mall_goods g','b.goods_id = g.id')
                ->with('goods')
                ->where($where)->paginate($limit)->toArray();
//            dump($this->model->getLastSql());exit();
            return Show::json_show(Status::lay_normal,"ok",$lists['data'],$lists['total']);
//            //获取时间
//            try {
////                $lists = $this->model->getPaginateByNormalListInfo(array_merge($where, $where1), $limit, $this->field,'id desc',['goods']);
//            }catch (\Exception $e){
//                return Show::json_show(Status::lay_error,$e->getMessage());
//            }
//            return Show::json_show(Status::lay_normal,"ok",$lists['data'],$lists['total']);
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation (title="添加砍价")
     * @return array|mixed|\think\response\Json
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            if(empty($post['bargain_time'])){
                return Show::json_show(Status::status_error,"请选择砍价时间");
            }
            list($start,$end) = explode('~',$post['bargain_time']);
            $post['start_time'] = strtotime($start);
            $post['end_time'] = strtotime($end);
            $rule = [
                "goods_id"=>"require|integer",
                "goods_cate"=>"require|integer",
                "logo"=>"require",
                "stock"=>"require|integer",
                "end_price"=>"require",
                "start_time"=>"require",
                "end_time"=>"require",
                "number"=>"require",
                "is_halfway"=>"require|integer",
                "is_number"=>"require|integer",
                "type"=>"require|integer",
                "rule"=>"require"
            ];
            $message = [
                "goods_id.require"=>"请选择商品",
                "goods_cate.require"=>"请选择商品规格",
                "logo.require"=>"请上传封面图",
                "stock.require"=>"请输入库存",
                "end_price.require"=>"请输入最低价格",
                "start_time.require"=>"请选择砍价时间",
                "end_time.require"=>"请选择砍价时间",
                "number.require"=>"请输入砍价人数",
                "is_halfway.require"=>"请选择是否中途下单",
                "is_number.require"=>"请选择是否限制次数",
                "type.require"=>"请选择砍价方式",
                "rule.require"=>"请输入砍价规则"
            ];
            $this->validate($post, $rule,$message);


            try {
                $save = $this->model->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败:'.$e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        return $this->fetch();
    }

    /**
     *
     * @param $id
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @NodeAnotation (title="编辑砍价")
     */
    public function edit($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            try {
                $save = $row->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $row['bargain_time'] = date('Y-m-d H:i:s',$row['start_time'])." ~ ".date('Y-m-d H:i:s',$row['end_time']);
        $this->assign('row', $row);
        return $this->fetch();
    }


}